import router from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { Route } from 'vue-router'
import { UserModule } from '@/store/modules/user'
import { config } from '@/microAppConfig'

NProgress.configure({ showSpinner: false })

const whiteList = [
  '/login',
  '/login/register',
  '/login/find-pwd',
  '/login/reset-pwd',
  '/login/success',
  '/login/success-email'
]

// 全局设置title
const getPageTitle = (key: string) => {
  return key
}

const isChildRoute = (path: string) =>
  config.some((item: any) => path.startsWith(item.activeRule))
const rawAppendChild = HTMLHeadElement.prototype.appendChild
const rawAddEventListener = window.addEventListener

// 所有路由拦截交给axios-response-code码处理
router.beforeEach(async (to: Route, from: Route, next: any) => {
  // Start progress bar
  NProgress.start()
  await UserModule.GetSysConfig()
  // 从子项目跳转到主项目
  if (isChildRoute(from.path) && !isChildRoute(to.path)) {
    console.log('从子项目跳转到主项目')

    HTMLHeadElement.prototype.appendChild = rawAppendChild
    window.addEventListener = rawAddEventListener
  }
  // Determine whether the user has logged in
  if (UserModule.token) {
    if (to.path === '/login') {
      // If is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      next()
    }
  } else {
    // Has no token
    if (whiteList.indexOf(to.path) !== -1) {
      // In the free login whitelist, go directly
      next()
    } else {
      // Other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach((to: Route) => {
  console.log('cccc')
  // Finish progress bar
  NProgress.done()
  // set page title
  document.title = getPageTitle(to.meta.title ? `星云管理后台` : '...')
})
